package com.wannengbang.storemobile.homepage;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wannengbang.storemobile.R;
import com.wannengbang.storemobile.base.BaseActivity;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BankAuthCodeBean;
import com.wannengbang.storemobile.bean.BankCardBean;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.bean.IdCardBean;
import com.wannengbang.storemobile.bean.ImageBean;
import com.wannengbang.storemobile.bean.StoreDeatilsBean;
import com.wannengbang.storemobile.event.IncreaseAuthEvent;
import com.wannengbang.storemobile.event.StoreDataEvent;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.homepage.model.IHomePageModel;
import com.wannengbang.storemobile.utils.Base64BitmapUtil;
import com.wannengbang.storemobile.utils.DateTimeUtil;
import com.wannengbang.storemobile.utils.GlideEngine;
import com.wannengbang.storemobile.utils.GlideUtils;
import com.wannengbang.storemobile.utils.PermissionsManager;
import com.wannengbang.storemobile.utils.ToastUtil;
import com.wannengbang.storemobile.widget.AppTitleBar;
import com.wannengbang.storemobile.widget.CountDownTimerButton;
import com.wannengbang.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddIncreaseAuthActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_settle_name)
    EditText tvSettleName;
    @BindView(R.id.tv_settle_mobile)
    EditText tvSettleMobile;
    @BindView(R.id.tv_id_card)
    EditText tvIdCard;
    @BindView(R.id.tv_card_no)
    EditText tvCardNo;
    @BindView(R.id.tv_valid_date)
    EditText tvValidDate;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.tv_send_code)
    CountDownTimerButton tvSendCode;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.iv_id_card_scan)
    ImageView ivIdCardScan;
    @BindView(R.id.iv_bank_scan)
    ImageView ivBankScan;
    private int length1;
    private int length2;
    private int length3;
    private int length4;
    private BankAuthCodeBean bankAuthCodeBean;

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private IHomePageModel homePageModel = new HomePageModelImpl();
    private int imgTpye;
    private String bank_name = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_increase_auth);
        ButterKnife.bind(this);
        initView();
        requestStoreProfile();
    }

    //    初始化请求
    private void initView() {
        permissionsManager = new PermissionsManager(AddIncreaseAuthActivity.this);
        tvSettleName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length1 = s.length();
                setEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvSettleMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length2 = s.length();
                setEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvIdCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length3 = s.length();
                setEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvCardNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                length4 = s.length();
                setEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvSendCode.setOnClickListener(v -> {
            sendCode();
        });
    }

    public void setEnable() {
        if (length1 > 0 && length2 > 0 && length3 > 0 && length4 > 0) {
            tvSendCode.setEnabled(true);
        } else {
            tvSendCode.setEnabled(false);
        }
    }

    public void sendCode() {
        String settleName = tvSettleName.getText().toString();
        String settleMobile = tvSettleMobile.getText().toString();
        String idCard = tvIdCard.getText().toString();
        String cardNo = tvCardNo.getText().toString();

        if (TextUtils.isEmpty(settleName)) {
            ToastUtil.showShort("请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(settleMobile)) {
            ToastUtil.showShort("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            ToastUtil.showShort("请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(cardNo)) {
            ToastUtil.showShort("请输入信用卡号");
            return;
        }

        new HomePageModelImpl().requestVerifyBankFourFactor(bank_name, settleName, settleMobile, idCard, cardNo, new DataCallBack<BankAuthCodeBean>() {
            @Override
            public void onSuccessful(BankAuthCodeBean bean) {
                ToastUtil.showShort("验证码发送成功");
                tvSendCode.startTimer();
                bankAuthCodeBean = bean;
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    public void requestStoreProfile() {
        homePageModel.requestStoreProfile(new DataCallBack<StoreDeatilsBean>() {
            @Override
            public void onSuccessful(StoreDeatilsBean bean) {
                if (!TextUtils.isEmpty(bean.getData().getHolder())) {
                    tvSettleName.setText(bean.getData().getHolder());
                    tvSettleName.setSelection(bean.getData().getHolder().length());
                }

                if (!TextUtils.isEmpty(bean.getData().getHolder_mobile())) {
                    tvSettleMobile.setText(bean.getData().getHolder_mobile());
                    tvSettleMobile.setSelection(bean.getData().getHolder_mobile().length());
                }

                if (!TextUtils.isEmpty(bean.getData().getHolder_id_card_no())) {
                    tvIdCard.setText(bean.getData().getHolder_id_card_no());
                    tvIdCard.setSelection(bean.getData().getHolder_id_card_no().length());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.tv_commit, R.id.iv_id_card_scan, R.id.iv_bank_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit:
                String settleName = tvSettleName.getText().toString();
                String settleMobile = tvSettleMobile.getText().toString();
                String idCard = tvIdCard.getText().toString();
                String cardNo = tvCardNo.getText().toString();

                if (TextUtils.isEmpty(settleName)) {
                    ToastUtil.showShort("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(settleMobile)) {
                    ToastUtil.showShort("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(idCard)) {
                    ToastUtil.showShort("请输入身份证号");
                    return;
                }
                if (TextUtils.isEmpty(cardNo)) {
                    ToastUtil.showShort("请输入信用卡号");
                    return;
                }
                if (bankAuthCodeBean == null) {
                    ToastUtil.showShort("请发送验证码");
                    return;
                }
                String code = editCode.getText().toString();
                String valid_date = tvValidDate.getText().toString();
                if (TextUtils.isEmpty(code)) {
                    ToastUtil.showShort("请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(valid_date)) {
                    ToastUtil.showShort("请输入信用卡有效期");
                    return;
                }
                requestUpAmount(bankAuthCodeBean.getData().getId(), code, valid_date);
                break;
            case R.id.iv_id_card_scan:
                imgTpye = 1;
                showPictureSelectorDialog();
                break;
            case R.id.iv_bank_scan:
                imgTpye = 2;
                showPictureSelectorDialog();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                ToastUtil.showShort("上传成功");
                if (imgTpye == 1) {
                    requestAliIdCard(bean.getData().getUrl(), "face");
                } else if (imgTpye == 2) {
                    requestAliBankCard(bean.getData().getUrl());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliIdCard(String imgPath, String side) {
        ViewLoading.showProgress(mActivity, "识别中......");
        homePageModel.requestAliIdCard(imgPath, side, new DataCallBack<IdCardBean>() {
            @Override
            public void onSuccessful(IdCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    if ("face".equals(side)) {
                        tvIdCard.setText(bean.getData().getNum());
                        if (!TextUtils.isEmpty(bean.getData().getNum())) {
                            tvIdCard.setSelection(bean.getData().getNum().length());
                        }
                    }
                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliBankCard(String imgPath) {
        homePageModel.requestAliBankCard(imgPath, new DataCallBack<BankCardBean>() {
            @Override
            public void onSuccessful(BankCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    bank_name = bean.getData().getBank_name();
                    tvCardNo.setText(bean.getData().getCard_num());
                    if (!TextUtils.isEmpty(bean.getData().getCard_num())) {
                        tvCardNo.setSelection(bean.getData().getCard_num().length());
                    }
                    if (!TextUtils.isEmpty(bean.getData().getValid_date())) {
                        tvValidDate.setText(bean.getData().getValid_date().replace("/", ""));
                    }
                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestUpAmount(String id, String sms_code, String valid_date) {
        ViewLoading.showProgress(mActivity);
        new HomePageModelImpl().requestUpAmount(id, sms_code, valid_date, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
                EventBus.getDefault().post(new IncreaseAuthEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(AddIncreaseAuthActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(AddIncreaseAuthActivity.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelPictureDialog();
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }

}
